package com.itc.dispatch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itc.common.core.domain.R;
import com.itc.common.core.utils.BeanCopyUtils;
import com.itc.common.core.utils.LocalDateTimeUtils;
import com.itc.common.core.utils.OkHttpUtil;
import com.itc.dispatch.common.BeanFlightCopy;
import com.itc.dispatch.common.Constents;
import com.itc.dispatch.common.SnakeTool;
import com.itc.dispatch.domain.*;
import com.itc.dispatch.domain.dto.DisFlightSearchConfigDto;
import com.itc.dispatch.domain.dto.DisFlightSearchValuePageDto;
import com.itc.dispatch.domain.dto.FlightDevicePageDto;
import com.itc.dispatch.domain.vo.AlarmCentreFlightVo;
import com.itc.dispatch.domain.vo.FieldVo;
import com.itc.dispatch.domain.vo.FlightLinkInfoVo;
import com.itc.dispatch.service.*;
import com.itc.dispatch.mapper.FlightOperationMonitoringMapper;
import com.itc.system.api.listener.CastAdsb;
import com.itc.system.api.listener.FlightGuaRantee;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
* @author 智少
* @description 针对表【flight_operation_monitoring】的数据库操作Service实现
* @createDate 2024-07-17 16:53:58
*/
@Service
public class FlightOperationMonitoringServiceImpl extends ServiceImpl<FlightOperationMonitoringMapper, FlightOperationMonitoring>
    implements FlightOperationMonitoringService{

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private FlightOperationMonitoringPtdService flightOperationMonitoringPtdService;

    @Autowired
    private FlightOperationMonitoringHistoryService flightOperationMonitoringHistoryService;

    @Autowired
    private FlightGuaRanteeService flightGuaRanteeService;

    @Autowired
    private FlightDeviceService flightDeviceService;

    @Autowired
    private FlightTimeExchangeService flightTimeExchangeService;

    @Autowired
    private AlarmCentreService alarmCentreService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public R<List<FieldVo>> getFiled() {
        //redis key定义
        String key="rediskey"+"fieldVo";
        Class<FlightOperationMonitoring> flightOperationMonitoringClass = FlightOperationMonitoring.class;
        Field[] declaredFields = flightOperationMonitoringClass.getDeclaredFields();
        ArrayList<FieldVo> fieldVos = new ArrayList<>();
        for (Field declaredField : declaredFields) {
            FieldVo fieldVo = new FieldVo();
            String name = declaredField.getName();
            String newName = SnakeTool.convertCamelToSnake(name);
            //添加驼峰，下划线名
            fieldVo.setFieldName(declaredField.getName());
            fieldVo.setFieldUnderName(newName);
            //获取注解value值
            fieldVo.setFieldRemark(declaredField.getAnnotation(ApiModelProperty.class).value());
            Class<?> type = declaredField.getType();
            int index = type.getName().lastIndexOf(".");
            if (index != -1){
                fieldVo.setType(type.getName().substring(index + 1));
            }
            fieldVos.add(fieldVo);
        }
        //redis 数据一致性校验
        List<FieldVo> redisList = (List<FieldVo>) redisTemplate.opsForValue().get(key);
        if ( redisList != null && redisList.equals(fieldVos)){
            return R.ok(redisList);
        }
        //首选清空redis存储
        redisTemplate.delete(key);
        //新增redis存储
        redisTemplate.opsForValue().set(key,fieldVos);
        return R.ok(fieldVos);
    }
    //根据筛选条件获取展示数据
    @Override
    public R<Page<FlightOperationMonitoring>> getSearch(Page page, DisFlightSearchValuePageDto dto) {
        List<DisFlightSearchConfigDto> disFlightSearchConfigDtoList = dto.getDisFlightSearchConfigDtoList();
        // 判断条件是否为0
        long count = disFlightSearchConfigDtoList.stream()
                .map(DisFlightSearchConfigDto::getFieldValue)
                .filter(value -> value != null && !value.trim().isEmpty()) // 过滤非空和非空字符串
                .count();
        if (count == 0){
            //默认返回当天的数据
            LocalDate today = LocalDate.now();
            //获取当天时间段
            LocalDateTime startOfDay = today.atStartOfDay();
            LocalDateTime endOfDay = today.atTime(LocalTime.MAX);
            LambdaQueryWrapper<FlightOperationMonitoring> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            //TODO 添加当天数据,测试完毕打开
//            lambdaQueryWrapper.between(FlightOperationMonitoring::getStdD,startOfDay,endOfDay);
            lambdaQueryWrapper.isNotNull(FlightOperationMonitoring::getFlightIdD);
            lambdaQueryWrapper.orderByDesc(FlightOperationMonitoring::getStdD);
            //返回全部信息
            Page resultPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
            return R.ok(resultPage);
        }
        QueryWrapper<FlightOperationMonitoring> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("flight_id_d");
        for (DisFlightSearchConfigDto disFlightSearchConfigDto : disFlightSearchConfigDtoList) {
            if (StringUtils.isNotBlank(disFlightSearchConfigDto.getFieldValue())){
                //文本类型
                if (disFlightSearchConfigDto.getSearchType().intValue()== Constents.Int_1 ) {
                    String fieldValue = disFlightSearchConfigDto.getFieldValue();
                    String fieldUnderName = disFlightSearchConfigDto.getFieldUnderName();
                    queryWrapper.like(fieldUnderName,fieldValue);
                }
                //日期类型
                else if (disFlightSearchConfigDto.getSearchType().intValue() == Constents.Int_3){
                    //获取选择的当天时间
                    LocalDate chooseDate = disFlightSearchConfigDto.getChooseDate();
                    LocalDateTime startDate = chooseDate.atStartOfDay();
                    LocalDateTime endDate = chooseDate.atTime(LocalTime.MAX);
                    String fieldUnderName = disFlightSearchConfigDto.getFieldUnderName();
                    queryWrapper.between(fieldUnderName, startDate,endDate);
                }
                //下拉框类型
                else {
                    String downValue = disFlightSearchConfigDto.getFieldValue();
                    String fieldUnderName = disFlightSearchConfigDto.getFieldUnderName();
                    queryWrapper.like(fieldUnderName,downValue);
                }
            }
        }

        Page resultPage = this.baseMapper.selectPage(page, queryWrapper);
        return R.ok(resultPage);
    }

    @Override
    public R<List<Object>> getDownSelectionList(DisFlightSearchValuePageDto dto) {
        if(StringUtils.isBlank(dto.getFieldUnderName())){
            return R.ok(new LinkedList<>());
        }
        List<DisFlightSearchConfigDto> disFlightSearchConfigDtoList = dto.getDisFlightSearchConfigDtoList();
        QueryWrapper<FlightOperationMonitoring> queryWrapper = new QueryWrapper<>();
        //用于判断是否通过时间来做了筛选
        Boolean stdStatus = true;
        if(dto.getDisFlightSearchConfigDtoList() != null){
            for (DisFlightSearchConfigDto disFlightSearchConfigDto : disFlightSearchConfigDtoList) {
                if (StringUtils.isNotBlank(disFlightSearchConfigDto.getFieldValue())){
                    //文本类型
                    if (disFlightSearchConfigDto.getSearchType().intValue()== Constents.Int_1 ) {
                        String fieldValue = disFlightSearchConfigDto.getFieldValue();
                        String fieldUnderName = disFlightSearchConfigDto.getFieldUnderName();
                        queryWrapper.like(fieldUnderName,fieldValue);
                    }
                    //日期类型
                    else if (disFlightSearchConfigDto.getSearchType().intValue() == Constents.Int_3){
                        stdStatus = false;
                        //获取选择的当天时间
                        String chooseDate = disFlightSearchConfigDto.getFieldValue();
                        String startDate = chooseDate+" 00:00:00";
                        String endDate = chooseDate+" 23:59:59";
                        String fieldUnderName = disFlightSearchConfigDto.getFieldUnderName();
                        queryWrapper.between(fieldUnderName, startDate,endDate);
                    }
                    //下拉框类型
                    else {
                        String downValue = disFlightSearchConfigDto.getFieldValue();
                        String fieldUnderName = disFlightSearchConfigDto.getFieldUnderName();
                        if(StringUtils.isNotBlank(downValue)){
                            queryWrapper.in(fieldUnderName,downValue.split(","));
                        }
                    }
                }
            }
        }

        if(stdStatus){
            LocalDate now = LocalDate.now();
//            LocalDateTime startOfDay = LocalDateTime.now();
            LocalDateTime startOfDay = LocalDateTime.of(now,LocalTime.MIN);
            LocalDateTime endOfDay = LocalDateTime.of(now,LocalTime.MAX);
            queryWrapper.between("std_d",startOfDay,endOfDay);
        }

        queryWrapper.isNotNull(dto.getFieldUnderName());
        queryWrapper.ne(dto.getFieldUnderName(),"");

        queryWrapper.select(dto.getFieldUnderName());
        queryWrapper.isNotNull("flight_id_d");
        queryWrapper.groupBy(dto.getFieldUnderName());
        List<Object> resultList = this.baseMapper.selectObjs(queryWrapper);
        return R.ok(resultList);
    }

    @Override
    public R<List<FlightOperationMonitoring>> getList(DisFlightSearchValuePageDto dto) {
        List<DisFlightSearchConfigDto> disFlightSearchConfigDtoList = dto.getDisFlightSearchConfigDtoList();
        QueryWrapper<FlightOperationMonitoring> queryWrapper = new QueryWrapper<>();
        //用于判断是否通过时间来做了筛选
        Boolean stdStatus = true;
        if(dto.getDisFlightSearchConfigDtoList() != null){
            for (DisFlightSearchConfigDto disFlightSearchConfigDto : disFlightSearchConfigDtoList) {
                if (StringUtils.isNotBlank(disFlightSearchConfigDto.getFieldValue())){
                    //文本类型
                    if (disFlightSearchConfigDto.getSearchType().intValue()== Constents.Int_1 ) {
                        String fieldValue = disFlightSearchConfigDto.getFieldValue();
                        String fieldUnderName = disFlightSearchConfigDto.getFieldUnderName();
                        queryWrapper.like(fieldUnderName,fieldValue);
                    }
                    //日期类型
                    else if (disFlightSearchConfigDto.getSearchType().intValue() == Constents.Int_3){
                        stdStatus = false;
                        //获取选择的当天时间
                        String chooseDate = disFlightSearchConfigDto.getFieldValue();
                        String startDate = chooseDate+" 00:00:00";
                        String endDate = chooseDate+" 23:59:59";
                        String fieldUnderName = disFlightSearchConfigDto.getFieldUnderName();
                        queryWrapper.between(fieldUnderName, startDate,endDate);
                    }
                    //下拉框类型
                    else {
                        String downValue = disFlightSearchConfigDto.getFieldValue();
                        String fieldUnderName = disFlightSearchConfigDto.getFieldUnderName();
                        if(StringUtils.isNotBlank(downValue)){
                            queryWrapper.in(fieldUnderName,downValue.split(","));
                        }
                    }
                }
            }
        }

        if(stdStatus){
            LocalDate now = LocalDate.now();
//            LocalDateTime startOfDay = LocalDateTime.now();
            LocalDateTime startOfDay = LocalDateTime.of(now,LocalTime.MIN);
            LocalDateTime endOfDay = LocalDateTime.of(now,LocalTime.MAX);
            queryWrapper.between("std_d",startOfDay,endOfDay);
        }
        queryWrapper.isNotNull("flight_id_d");
        queryWrapper.orderByAsc("std_d");
        List<FlightOperationMonitoring> resultList = this.baseMapper.selectList(queryWrapper);

        for (FlightOperationMonitoring monitoring : resultList) {
            if(StringUtils.isNotBlank(monitoring.getPtd())){
                LocalDateTime ptd = LocalDateTimeUtils.stringToLocalDateTime(monitoring.getPtd(),"yyyy-MM-dd HH:mm:ss");
                if(StringUtils.isNotBlank(monitoring.getNormalTakeoffTime())){
                    LocalDateTime takeOffTime = LocalDateTimeUtils.stringToLocalDateTime(monitoring.getNormalTakeoffTime(),"yyyy-MM-dd HH:mm:ss");
                    Duration duration = Duration.between(takeOffTime, ptd);
                    Long time = duration.toMinutes();
                    if(time > 0){
                        monitoring.setPre_takeoff_delay_min(time);
                    }
                }
                if(StringUtils.isNotBlank(monitoring.getNormalReleaseTime())){
                    LocalDateTime releaseTime = LocalDateTimeUtils.stringToLocalDateTime(monitoring.getNormalReleaseTime(),"yyyy-MM-dd HH:mm:ss");
                    Duration duration = Duration.between(releaseTime, ptd);
                    Long time = duration.toMinutes();
                    if(time > 0){
                        monitoring.setPre_release_delay_min(duration.toMinutes());
                    }
                }
            }
        }
        
        
        if(resultList.size() == 0){
            return R.ok(resultList);
        }
        List<String> flightIds = resultList.stream().map(FlightOperationMonitoring::getFlightIdD).collect(Collectors.toList());

        //查询关联的流程数量信息
        for (FlightOperationMonitoring flightOperationMonitoring : resultList) {
            if(StringUtils.isBlank(flightOperationMonitoring.getFlightIdD())){
                continue;
            }
            flightOperationMonitoring.setBpmCount("2-5");
        }


        //查询关联的告警
        List<AlarmCentreFlightVo> alarmList = alarmCentreService.getFlightAlarmList(flightIds);
        if(alarmList.size() > 0){
            Map<String,List<AlarmCentreFlightVo>> alarmMap = alarmList.stream().collect(Collectors.groupingBy(AlarmCentreFlightVo::getFlightId));
            for (FlightOperationMonitoring flightOperationMonitoring : resultList) {
                if(StringUtils.isBlank(flightOperationMonitoring.getFlightIdD())){
                    continue;
                }
                flightOperationMonitoring.setAlarmList(alarmMap.get(flightOperationMonitoring.getFlightIdD()));
            }
        }

        List<FlightTimeExchange> exchangeList = flightTimeExchangeService.getBaseMapper().selectList(
                new LambdaQueryWrapper<FlightTimeExchange>()
                .in(FlightTimeExchange::getFlt1Id,flightIds)
        );

        if(exchangeList.size() == 0){
            return R.ok(resultList);
        }

        Map<String,List<FlightTimeExchange>> changeMap = exchangeList.stream().collect(Collectors.groupingBy(FlightTimeExchange::getFlt1Id));
        for (FlightOperationMonitoring flightOperationMonitoring : resultList) {
            if(StringUtils.isBlank(flightOperationMonitoring.getFlightIdD())){
                continue;
            }
            if(changeMap.get(flightOperationMonitoring.getFlightIdD()) != null){
                flightOperationMonitoring.setTimeChangeStatus(1);
            }
        }

        return R.ok(resultList);
    }

    @Override
    public R<Page<FlightDevice>> getFlightVideoPage(Page page, FlightDevicePageDto pageDto) {
        if(StringUtils.isBlank(pageDto.getFlightId())){
            return R.fail("航班信息ID不能为空");
        }
        FlightOperationMonitoring monitoring = this.baseMapper.selectOne(
                new LambdaQueryWrapper<FlightOperationMonitoring>()
                .eq(FlightOperationMonitoring::getId,pageDto.getFlightId())
                .last("limit 1")
        );
        if(monitoring == null){
            return R.fail("航班信息异常");
        }
        String[] gateList = null;
        String[] craftList = null;
        if(StringUtils.isNotBlank(monitoring.getGateCode())){
            //登机口
            gateList = monitoring.getGateCode().split(",");
            pageDto.setGateList(gateList);
        }
        if(StringUtils.isNotBlank(monitoring.getCraftSiteD())){
            //机位
            craftList = monitoring.getCraftSiteD().split(",");
            pageDto.setCraftList(craftList);
        }
        if(gateList == null && craftList == null){
            return R.ok(new Page<>());
        }
        Page<FlightDevice> resultPage = flightDeviceService.getFlightVideoPage(page,pageDto);
        return R.ok(resultPage);
    }

    @Override
    public R<List<CastAdsb>> getFlightGisList(String flightId) {
        FlightOperationMonitoring monitoring = this.baseMapper.selectById(flightId);
        if(monitoring == null){
            return R.fail("航班信息异常");
        }
        if(StringUtils.isBlank(monitoring.getFlightIdD())){
            return R.ok(new LinkedList<>());
        }
        List<CastAdsb> resultList = this.baseMapper.getFlightGisList(monitoring.getFlightIdD());
        return R.ok(resultList);
    }

    @Override
    public R<List<FlightLinkInfoVo>> getFlightLinkList(String flightId) {
        FlightOperationMonitoring monitoring = this.baseMapper.selectById(flightId);
        if(monitoring == null){
            return R.fail("航班信息异常");
        }
        List<FlightLinkInfoVo> resultList = new LinkedList<>();
        if(StringUtils.isBlank(monitoring.getFlightIdD())){
            return R.ok(resultList);
        }
        //api获取宽表数据
        Object resultObj = OkHttpUtil.sendOkHttpClient("http://172.23.80.2:8080/data/getLinkFlightInfo?flight_id="+monitoring.getFlightIdD()
                , "GET",null,null);
        if(resultObj == null){
            return R.ok(resultList);
        }
        JSONObject dataJson = JSONObject.parseObject(resultObj.toString());
        if(!"200".equals(dataJson.getString("code"))){
            return R.ok(resultList);
        }
        JSONObject detailJson = dataJson.getJSONObject("data");
        //当前航班
        FlightLinkInfoVo currentFlight = JSONObject.parseObject(detailJson.toJSONString(),FlightLinkInfoVo.class);

        //宽表里面的进港实际起飞 atd_a  进港时间落地 ata_a  出港实际起飞 atd_d    出港实际落地 ata_d
        //预计落地时间  宽表里面进港的就是 eta_a  出港的是 eta_d   没有在宽表就是接口的是 eldt
        currentFlight.setAct_take_off(monitoring.getAtdD());
        currentFlight.setAct_arrived(monitoring.getAtaD());
        currentFlight.setPre_arrived(StringUtils.isNotBlank(monitoring.getEtaD()) ? monitoring.getEtaD() : currentFlight.getEldt());

        //前序航班
        if(detailJson.get("previous_flight") != null){
            JSONObject preJson2 = detailJson.getJSONObject("previous_flight");
            FlightLinkInfoVo preFlight2 = JSONObject.parseObject(preJson2.toJSONString(),FlightLinkInfoVo.class);
            preFlight2.setType(0);

            preFlight2.setAct_take_off(monitoring.getAtdA());
            preFlight2.setAct_arrived(monitoring.getAtaA());
            preFlight2.setPre_arrived(StringUtils.isNotBlank(monitoring.getEtaA()) ? monitoring.getEtaA() : preFlight2.getEldt());

            if(preJson2.get("previous_flight") != null){
                JSONObject preJson1 = preJson2.getJSONObject("previous_flight");
                FlightLinkInfoVo preFlight1 = JSONObject.parseObject(preJson1.toJSONString(),FlightLinkInfoVo.class);
                preFlight1.setType(0);
                resultList.add(preFlight1);
                resultList.add(preFlight2);
            }else{
                resultList.add(preFlight2);
            }
        }
        currentFlight.setType(1);
        resultList.add(currentFlight);
        //后序航班
        if(detailJson.get("next_flight") != null){
            JSONObject preJson2 = detailJson.getJSONObject("next_flight");
            FlightLinkInfoVo preFlight2 = JSONObject.parseObject(preJson2.toJSONString(),FlightLinkInfoVo.class);
            preFlight2.setType(2);
            if(preJson2.get("next_flight") != null){
                JSONObject preJson1 = preJson2.getJSONObject("next_flight");
                FlightLinkInfoVo preFlight1 = JSONObject.parseObject(preJson1.toJSONString(),FlightLinkInfoVo.class);
                preFlight1.setType(2);
                resultList.add(preFlight1);
                resultList.add(preFlight2);
            }else{
                resultList.add(preFlight2);
            }
        }
        return R.ok(resultList);
    }

    @Override
    public R<List<FlightTimeExchange>> getTimeExchange(String flightId) {
        FlightOperationMonitoring monitoring = this.baseMapper.selectById(flightId);
        if(monitoring == null){
            return R.fail("航班信息异常");
        }
        List<FlightTimeExchange> resultList = new LinkedList<>();
        if(StringUtils.isBlank(monitoring.getFlightIdD())){
            return R.ok(resultList);
        }
        resultList = flightTimeExchangeService.getBaseMapper().selectList(
                new LambdaQueryWrapper<FlightTimeExchange>()
                .eq(FlightTimeExchange::getFlt1Id,monitoring.getFlightIdD())
        );
        return R.ok(resultList);
    }

    @Override
    public R<List<Object>> getDown(FieldVo dto) {
        if (dto.getFieldName() == null){
            return R.fail("查询结果有误");
        }
        QueryWrapper<FlightOperationMonitoring> wrapper = new QueryWrapper<>();
        String fieldUnderName = dto.getFieldUnderName();
        wrapper.select(fieldUnderName).groupBy(fieldUnderName);
        List<Object> list = this.baseMapper.selectObjs(wrapper);
        return R.ok(list);
    }



    //保障信息界面修改/保存
    @Override
    public R saveAssurance(FlightOperationMonitoring dto) {
        FlightOperationMonitoring operationMonitoring = this.baseMapper.selectById(dto.getId());
        if (operationMonitoring == null){
            return R.fail("信息存在错误");
        }
        BeanFlightCopy.copyPropertiesIgnoreNull(dto,operationMonitoring);
        this.baseMapper.updateById(operationMonitoring);
        return R.ok("修改信息成功");
    }


    @Override
    public R<FlightOperationMonitoring> detail(String id) {
        FlightOperationMonitoring operationMonitoring = this.baseMapper.selectById(id);
        if (operationMonitoring == null){
            return R.fail("查询数据有误");
        }
        if(StringUtils.isNotBlank(operationMonitoring.getPtd())){
            LocalDateTime ptd = LocalDateTimeUtils.stringToLocalDateTime(operationMonitoring.getPtd(),"yyyy-MM-dd HH:mm:ss");
            if(StringUtils.isNotBlank(operationMonitoring.getNormalTakeoffTime())){
                LocalDateTime takeOffTime = LocalDateTimeUtils.stringToLocalDateTime(operationMonitoring.getNormalTakeoffTime(),"yyyy-MM-dd HH:mm:ss");
                Duration duration = Duration.between(takeOffTime, ptd);
                Long time = duration.toMinutes();
                if(time > 0){
                    operationMonitoring.setPre_takeoff_delay_min(time);
                }
            }
            if(StringUtils.isNotBlank(operationMonitoring.getNormalReleaseTime())){
                LocalDateTime releaseTime = LocalDateTimeUtils.stringToLocalDateTime(operationMonitoring.getNormalReleaseTime(),"yyyy-MM-dd HH:mm:ss");
                Duration duration = Duration.between(releaseTime, ptd);
                Long time = duration.toMinutes();
                if(time > 0){
                    operationMonitoring.setPre_release_delay_min(duration.toMinutes());
                }
            }
        }
        //查询保障信息列表
        List<FlightGuaRantee> ranteeList = flightGuaRanteeService.getBaseMapper().selectList(
                new LambdaQueryWrapper<FlightGuaRantee>()
                .eq(FlightGuaRantee::getFlightId,operationMonitoring.getFlightIdD())
                .orderByDesc(FlightGuaRantee::getDdtm)
        );
        if(ranteeList.size() == 0){
            return R.ok(operationMonitoring);
        }
        Map<String,List<FlightGuaRantee>> ranteeMap = ranteeList.stream().collect(Collectors.groupingBy(FlightGuaRantee::getNodeName));
        if(ranteeMap.get("飞机入位") != null){
            //航空器入位
            operationMonitoring.setAircraftLanding(ranteeMap.get("飞机入位").get(0).getCodeTime());
        }
        if(ranteeMap.get("廊桥靠桥") != null){
            //靠桥对接
            operationMonitoring.setBridgeDocking(ranteeMap.get("廊桥靠桥").get(0).getCodeTime());
        }
        if(ranteeMap.get("客梯车对接") != null){
            //客梯车对接
            operationMonitoring.setPassengerElevatorCardocking(ranteeMap.get("客梯车对接").get(0).getCodeTime());
        }
        if(ranteeMap.get("开客舱门") != null){
            //开客舱门
            operationMonitoring.setOpenPassengerdoor(ranteeMap.get("开客舱门").get(0).getCodeTime());
        }
        if(ranteeMap.get("关客舱门") != null){
            //关客舱门
            operationMonitoring.setClosePassengerdoor(ranteeMap.get("关客舱门").get(0).getCodeTime());
        }
        //开始下客?完成下客?
        if(ranteeMap.get("客舱清洁开始") != null){
            //开始清洁
            operationMonitoring.setBeginClean(ranteeMap.get("客舱清洁开始").get(0).getCodeTime());
        }
        if(ranteeMap.get("客舱清洁结束") != null){
            //完成清洁
            operationMonitoring.setEndClean(ranteeMap.get("客舱清洁结束").get(0).getCodeTime());
        }
        if(ranteeMap.get("加油开始") != null){
            //开始加油
            operationMonitoring.setBeginCheer(ranteeMap.get("加油开始").get(0).getCodeTime());
        }
        if(ranteeMap.get("加油结束") != null){
            //完成加油
            operationMonitoring.setEndCheer(ranteeMap.get("加油结束").get(0).getCodeTime());
        }
        if(ranteeMap.get("上客摆渡车") != null){
            //出港摆渡车
            operationMonitoring.setDFerrybus(ranteeMap.get("上客摆渡车").get(0).getCodeTime());
        }
        // 货邮行装载?
        if(ranteeMap.get("开货舱门") != null){
            //开货舱门
            operationMonitoring.setOpenFreightdoor(ranteeMap.get("开货舱门").get(0).getCodeTime());
        }
        if(ranteeMap.get("关货舱门") != null){
            //关货舱门
            operationMonitoring.setCloseFreightdoor(ranteeMap.get("关货舱门").get(0).getCodeTime());
        }
        if(ranteeMap.get("航空器推出") != null){
            //航空器推出
            operationMonitoring.setAircraftDetrusion(ranteeMap.get("航空器推出").get(0).getCodeTime());
        }
        if(ranteeMap.get("牵引车到位") != null){
            //牵引车到位
            operationMonitoring.setTractorInPosition(ranteeMap.get("牵引车到位").get(0).getCodeTime());
        }
        if(ranteeMap.get("机组到位") != null){
            //机组到位
            operationMonitoring.setUnitInPlace(ranteeMap.get("机组到位").get(0).getCodeTime());
        }
        //机组退场?旅客离场?
        if(ranteeMap.get("放轮档") != null){
            //上轮挡
            operationMonitoring.setTopBumper(ranteeMap.get("放轮档").get(0).getCodeTime());
        }
        if(ranteeMap.get("开始排污") != null){
            //开始排污
            operationMonitoring.setStartBlowdown(ranteeMap.get("开始排污").get(0).getCodeTime());
        }
        if(ranteeMap.get("完成排污") != null){
            //完成排污
            operationMonitoring.setEndBlowdown(ranteeMap.get("完成排污").get(0).getCodeTime());
        }
        if(ranteeMap.get("开始配餐") != null){
            //开始配餐
            operationMonitoring.setStartMeal(ranteeMap.get("开始配餐").get(0).getCodeTime());
        }
        if(ranteeMap.get("完成配餐") != null){
            //完成配餐
            operationMonitoring.setEndMeal(ranteeMap.get("完成配餐").get(0).getCodeTime());
        }
        if(ranteeMap.get("撤轮档") != null){
            //撤轮挡
            operationMonitoring.setDownBumper(ranteeMap.get("撤轮档").get(0).getCodeTime());
        }
        if(ranteeMap.get("下客摆渡车") != null){
            //进港摆渡车
            operationMonitoring.setAFerrybus(ranteeMap.get("下客摆渡车").get(0).getCodeTime());
        }
        if(ranteeMap.get("机务放行") != null){
            //机务放行
            operationMonitoring.setMaintenanceRelease(ranteeMap.get("机务放行").get(0).getCodeTime());
        }

        if(ranteeMap.get("接机保障") != null){
            //接机保障
            operationMonitoring.setAirportTransfer(ranteeMap.get("接机保障").get(0).getCodeTime());
        }
        if(ranteeMap.get("传送带车") != null){
            //传送带车
            operationMonitoring.setConveyerBelt(ranteeMap.get("传送带车").get(0).getCodeTime());
        }
        if(ranteeMap.get("电源车") != null){
            //电源车
            operationMonitoring.setPowerVan(ranteeMap.get("电源车").get(0).getCodeTime());
        }
        if(ranteeMap.get("气源车") != null){
            //气源车
            operationMonitoring.setAirSourceTrailor(ranteeMap.get("气源车").get(0).getCodeTime());
        }
        if(ranteeMap.get("空调车") != null){
            //空调车
            operationMonitoring.setAirConditioner(ranteeMap.get("空调车").get(0).getCodeTime());
        }
        if(ranteeMap.get("送机保障") != null){
            //送机保障
            operationMonitoring.setDeliveryGuarantee(ranteeMap.get("送机保障").get(0).getCodeTime());
        }
        if(ranteeMap.get("残疾人平台车") != null){
            //残疾人平台车
            operationMonitoring.setDisabledPlatformCar(ranteeMap.get("残疾人平台车").get(0).getCodeTime());
        }
        if(ranteeMap.get("舱单上传") != null){
            //舱单上传
            operationMonitoring.setUploadManifest(ranteeMap.get("舱单上传").get(0).getCodeTime());
        }
        return R.ok(operationMonitoring);
    }

    @Override
//    @Transactional(isolation = Isolation.SERIALIZABLE)
    public void monitorDataUpdate() {
        //api获取宽表数据
        Object resultObj = OkHttpUtil.sendOkHttpClient("http://172.23.80.1:8081/airport/queryDynAllData"
                , "GET",null,null);
        if(resultObj == null){
            return;
        }
        JSONObject dataJson = JSONObject.parseObject(resultObj.toString());
        if(!"0000000".equals(dataJson.getString("resultCode"))){
            return;
        }
        try{
            List<FlightOperationMonitoring> monitoringList = objectMapper.readValue(dataJson.getString("resultData")
                    ,new TypeReference<List<FlightOperationMonitoring>>(){});

            Long timeStart = System.currentTimeMillis();

            int num = 0;
            if(monitoringList.size() > 0){
                List<String> ids = monitoringList.stream().map(FlightOperationMonitoring::getId).collect(Collectors.toList());

                this.baseMapper.delete(new LambdaQueryWrapper<FlightOperationMonitoring>().notIn(FlightOperationMonitoring::getId,ids));
                Long timeDel = System.currentTimeMillis();

                for (FlightOperationMonitoring monitoring : monitoringList) {
                    if(StringUtils.isBlank(monitoring.getStdD())){
                        continue;
                    }
                    if(monitoring.getStdD().indexOf(LocalDate.now().toString()) < 0){
                        continue;
                    }
                    if(StringUtils.isNotBlank(monitoring.getAirlinesIataD())){
                        monitoring.setFlightNoD(monitoring.getAirlinesIataD() + monitoring.getFlightNoD());
                    }
                    if(StringUtils.isNotBlank(monitoring.getAirlinesIataA())){
                        monitoring.setFlightNoA(monitoring.getAirlinesIataA() + monitoring.getFlightNoA());
                    }
                    num ++;
                    this.saveOrUpdate(monitoring);
                }
//                this.saveOrUpdateBatch(monitoringList);

//                this.updateBatchById(monitoringList,50);

                //数据同步更新到历史表
//                List<FlightOperationMonitoringHistory> monitoringHistories = BeanCopyUtils.copyList(monitoringList,FlightOperationMonitoringHistory.class);
//                flightOperationMonitoringHistoryService.saveOrUpdateBatch(monitoringHistories,500);
            }
            log.error("航班数据同步数量======="+num);
            Long timeEnd = System.currentTimeMillis();
            log.error("航班数据同步消耗时间======="+(timeEnd - timeStart));
            jdbcTemplate.execute("VACUUM FULL VERBOSE ANALYZE flight_operation_monitoring");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

}




